import { AddArticleCommnetResponse, ArticleCommentResponse, ArticlesDetailResponse } from '@/types/data.d.'
import request from '@/utils/request'
import { AppThunk } from '../index'
import { add, addComment, change, setComment } from '../modules/article'
// 3. 异步action
export const getArticleAction = (payload: string): AppThunk => {
  return async (dispatch, getState) => {
    const res: ArticlesDetailResponse = await request.get('/articles/' + payload)
    // console.log(res)
    dispatch(add(res.data))
  }
}

// 关注作者
export const followAction = (payload: string): AppThunk => {
  return async (dispatch, getState) => {
    await request.post('/user/followings', {
      target: payload,
    })
    dispatch(change({ is_followed: true }))
  }
}
// 取关作者
export const unFollowAction = (payload: string): AppThunk => {
  return async (dispatch, getState) => {
    await request.delete(`/user/followings/${payload}`)
    dispatch(change({ is_followed: false }))
  }
}
// 点赞作品
export const giveLikeAction = (payload: { id: string, count: number }): AppThunk => {
  return async (dispatch, getState) => {
    await request.post('/article/likings', {
      target: payload.id,
    })
    dispatch(change({ attitude: 1, like_count: payload.count }))
  }
}
// 取消点赞
export const unGiveLikeAction = (payload: { id: string, count: number }): AppThunk => {
  return async (dispatch, getState) => {
    await request.delete(`/article/likings/${payload.id}`)
    dispatch(change({ attitude: 0, like_count: payload.count }))
  }
}
// 收藏作品
export const collectAction = (payload: string): AppThunk => {
  return async (dispatch, getState) => {
    await request.post('/article/collections', {
      target: payload,
    })
    dispatch(change({ is_collected: true }))
  }
}
// 取消收藏
export const unCollectAction = (payload: string): AppThunk => {
  return async (dispatch, getState) => {
    await request.delete(`/article/collections/${payload}`)
    dispatch(change({ is_collected: false }))
  }
}

type Params = {
  type: string,
  source: string,
  offset?: string | null
  limit?: number
}

// 获取文章品论
export const getCommentsAPI = (payload: Params): AppThunk => {
  return async (dispatch, getState) => {
    const res: ArticleCommentResponse = await request.get('/comments', {
      params: payload
    })
    console.log('res', res)
    dispatch(setComment(res.data))
  }
}
type ComProps = {
  payload: {
    target: string
    content: string
    art_id?: string
  }
  count: number
}
// 发布文章品论
export const pubCommentsAPI = (body: ComProps): AppThunk => {
  return async (dispatch, getState) => {
    const res: AddArticleCommnetResponse = await request.post('/comments', body.payload)
    console.log('res', res)
    dispatch(addComment(res.data))
    dispatch(change({ comm_count: body.count }))
  }
}